import axios from "axios";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

//创建axios对象
// const baseURL = 'http://localhost:8080'
const baseURL = '/api'
//这个service和axios具有相同的功能
const service = axios.create({baseURL})

//请求拦截器
service.interceptors.request.use(req => {
    req.headers.role = 'user';
    //携带token，只要有token就携带token
    const tokenStore = useTokenStore();
    if(tokenStore.tokenStr) {
        req.headers.Authorization = tokenStore.tokenStr;
    }
    return req;
}, error => {

});
//响应拦截器
service.interceptors.response.use(response => {
    //返回result
    //return response.data
    //判断业务状态码为0，代表本次操作成功 或者  二进制数据则直接返回
    if (response.data.code == 0 || response.request.responseType ===  'blob') {
        //刷新token
        const token = response.headers.token;
        if(token) {
            const tokenStore = useTokenStore();
            tokenStore.updateToken(token);
        }
        return response.data;
    } else {
        //操作失败，走到这里代表业务状态码不是0，本次操作失败
        ElMessage.error(response.data.msg ? response.data.msg : '服务异常')
        return response.data;
    }
}, error => {
    //401 - 令牌
    if(error.status == 401) {
        ElMessage.error({
            message: '令牌错误，请重新登录',
            duration: 1200,
            onClose: () => { //提示信息消失时的回调
                //将store中的token和user设置为初值
                const tokenStore = useTokenStore();
                const userStore = useUserStore();
                tokenStore.$reset();
                userStore.$reset();
                let currentPath = router.currentRoute.value.path;
                router.push('/login');
            }
        });
        return Promise.reject(error);//异步的状态转化成失败的状态
    }
});

export default service;